<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发送请求</title>
    <script src="./node_module/axios/dist/mine-axios.js"></script>
</head>
<body>
    <script>
        function InterceptorManager(){
            this.handlers = []
        }
        InterceptorManager.prototype.use = function(onFulfilled, onRejected){
            this.handlers.push({
                onFulfilled,
                onRejected
            })
        }

        function Axios(config){
            this.defaults = config;
            this.interceptors = {
                request: new InterceptorManager(),
                response: new InterceptorManager()
            }
        }

        Axios.prototype.request = function(config){
            // 发送请求
            let dispatchRequest = function(){
                return Promise.resolve('用户列表数据')
            }
            // 声明队列 chain
            let chain = [dispatchRequest, undefined];
            // 添加请求拦截器
            this.interceptors.request.handlers.forEach(item=>{
                chain.unshift(item.onFulfilled,item.onRejected);
            })
            // 添加响应拦截器
            this.interceptors.response.handlers.forEach(item=>{
                chain.push(item.onFulfilled,item.onRejected);
            });
            // 清空 chain队列
            // 创建一个promise 用来启动队列then 方法
            let promise = Promise.resolve();
            while(chain.length){
                promise = promise.then(chain.shift(),chain.shift());
            }
            return promise;
        }

        let axios = new Axios({method:'get'});

        axios.interceptors.request.use(config1=>{
            console.log('请求拦截器 成功  1');
            return config1
        },error1=>{
            console.log('请求拦截器 失败 1 ');
            return Promise.reject(error1);
        });

        axios.interceptors.request.use(config2=>{
            console.log('请求拦截器 成功  2');
            return Promise.reject('我失败了，不活了');
            // return config2
        },error2=>{
            console.log('请求拦截器 失败 2 ');
            return Promise.reject(error2);
        })

        axios.interceptors.response.use(config1=>{
            console.log('响应拦截器 成功  1');
            return config1
        },error1=>{
            console.log('响应拦截器 失败 1 ');
            return Promise.reject(error1);
        })
        axios.interceptors.response.use(config2=>{
            console.log('响应拦截器 成功  2');
            return config2
        },error2=>{
            console.log('响应拦截器 失败 2 ');
            return Promise.reject(error2);
        })


        axios.request({method:'get'})
        .then(response=>{
            console.log(response);
        },error=>{
            console.log(error);
        });
    </script>
</body>
</html>